package mia.chat.api;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import mia.core.model.MiaUser;
import mia.core.service.MiaUserServiceLocal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/api/*")
public class AuthenticateController extends BaseController {
	
	@Autowired
	private MiaUserServiceLocal miaUserService;
	
	@RequestMapping(value = "auth/login", method = RequestMethod.POST)
	public ModelAndView getFund(@RequestBody MiaUser miaUser,
			HttpServletResponse httpResponse, WebRequest request) {
		
		System.out.println("username: " + miaUser.getUserLogin());
		System.out.println("password: " + miaUser.getPassword());
		
		MiaUser user = miaUserService.getUserByUserLogin(miaUser.getUserLogin());		// get user in database
		
		if (user == null || !user.getPassword().equals(miaUser.getPassword())) {
			String sMessage = "Tai khoan khong ton tai";
			return createErrorResponse(sMessage);
		}
		
		/* set HTTP response code */  
		httpResponse.setStatus(HttpStatus.CREATED.value());								// set HTTP response code
		
		return new ModelAndView(jsonView, DATA_FIELD, user);
	}
	
	@RequestMapping(value="person", method = RequestMethod.POST)
	public @ResponseBody MiaUser post(@RequestBody final MiaUser miaUser) {    
	 
		System.out.println(miaUser.getId() + " " + miaUser.getUserLogin());
		return miaUser;
	}
	
	@RequestMapping(value="languages", method = RequestMethod.GET)
	public @ResponseBody List<MiaUser> post(String root, HttpServletResponse httpResponse) {
		List<MiaUser> list = new ArrayList<MiaUser>();
		
		System.out.println("root: " + root);
		
		MiaUser user = new MiaUser();
		user.setId(1);
		user.setUserLogin("datnh");
		
		list.add(user);
		
		httpResponse.setContentType("application/json; charset=utf-8");
		
		return list;
	}
}
